<template>
  <!-- 设备配置 -->
  <div class="others table-flex-wrapper">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="" prop="grade">
        <selector ref="typeSelector" type="otherDeviceType" size="small" style="width: 160px" clearable placeholder="请选择设备类型"
          v-model="queryParams.deviceType"></selector>
      </el-form-item>
      <el-form-item label="" prop="grade">
        <selector ref="statusSelector" type="sensorState" size="small" style="width: 160px" clearable placeholder="请选择设备状态"
          v-model="queryParams.state"></selector>
      </el-form-item>
      <el-form-item label="" prop="keywords">
        <el-input v-model="queryParams.deviceName" placeholder="模糊搜索设备名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="keywords">
        <el-input v-model="queryParams.number" placeholder="模糊搜索设备编号" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" @click="handleQuery" type="primary">搜索</el-button>
        <el-button size="mini" @click="handleAdd" type="primary">新增</el-button>
        <el-button size="mini" @click="handleImport" type="primary">批量导入</el-button>
        <el-button size="mini" @click="handleExport" type="primary">导出</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table v-loading="loading" size="mini" :data="list">
      <el-table-column prop="seq" label="序号" width="70" align="center"></el-table-column>
      <el-table-column prop="name" label="设备名称" min-width="120" align="center"></el-table-column>
      <el-table-column prop="deviceType" label="设备类型" align="center" :formatter="typeFormat"></el-table-column>
      <el-table-column prop="deviceState" label="在线状态" align="center" :formatter="stateFormat"></el-table-column>
      <el-table-column prop="supplierName" min-width="160" show-overflow-tooltip label="设备供应商" align="center"></el-table-column>
      <el-table-column prop="supplyRepo" min-width="120" label="供应商联系人" align="center">
      </el-table-column>
      <el-table-column prop="supplyPhone" min-width="120" label="联系人电话" align="center">
      </el-table-column>
      <el-table-column prop="number" min-width="120" label="设备编号" align="center"></el-table-column>
      <el-table-column prop="imei" label="通信设备IMEI" min-width="120" align="center"></el-table-column>
      <el-table-column prop="position" min-width="160" label="坐标位置" align="center"></el-table-column>
      <el-table-column prop="operation" label="操作" width="200" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" class="btn" @click="handleEdit(scope.row)" v-hasPermi="['system:role:edit']">编辑</el-button>
          <el-button size="mini" class="btn" @click="handleEnable(scope.row)" v-hasPermi="['system:role:edit']" v-if="scope.row.deviceIsValid!='0'">启用</el-button>
          <el-button size="mini" class="btn" @click="handleDisable(scope.row)" v-hasPermi="['system:role:edit']" v-if="scope.row.deviceIsValid=='0'">停用</el-button>
          <el-button size="mini" class="btn white" type="primary" @click="deleteInfo(scope.row.seq)" v-hasPermi="['slope:device:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <Add ref="add" @refresh="getList"></Add>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的设备数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Add from "./add";
  import { getToken } from "@/utils/auth";
  import { listOtherDevice, changeIsValid, exportOtherDevice, importDevice, importTemplate } from '@/api/page/device.js';
  import { delDevice } from '@/api/slope/device.js';
  import selector from "@/views/components/selector";
  export default {
    name: "others",
    components: {
      Add,
      selector
    },
    data() {
      return {
        // 角色表格数据
        list: [],
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deviceType: undefined,
          state: undefined,
          deviceName: undefined,
          number: undefined
        },
        optionsFrom: {
          typeOptions: [],
          statusOptions: []
        },
        // 导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/slope/device/importDevice"
		    },
		    // 导出加载框
        exportLoading: {
          lock: true,
          text: '正在导出文件，请稍等',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        },
      };
    },
    created() {
      let self=this;
      self.getDicts("device_type").then(response => {
        self.optionsFrom.typeOptions = response.data;
      }).catch((error)=>{
        console.log(error);
      });
      this.getList();
    },
    methods: {
      /**
       * 删除其它设备信息
       * @param id 其它设备id
       */
      deleteInfo(id) {
        let self = this;
         self.$confirm( "确认要删除该条信息吗?", "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          })
          .then(function() {
            delDevice(id).then((res)=>{
              if(res.code==200){
                self.msgSuccess(res.msg);
                self.getList();
              }else{
                self.msgError(res.msg);
              }
            }).catch(()=>{
              self.getList();
            });;

          })
          .then(() => {
            self.getList();
          })
          .catch(function(e) {
        });
      },
      /** 查询角色列表 */
      getList() {
        let self = this;
        self.loading = true;
        listOtherDevice(this.addDateRange(this.queryParams, this.dateRange))
          .then(response => {
            var data = response.rows;
            self.total = response.total;
            var tableData = [];
            for (var i = 0; i < data.length; i++) {
              var device = data[i];
              var supply = device.supplier;
              var point = device.point;
              if (supply == null) {
                supply = {
                  supplierId: null,
                  supplierName: null,
                  supplierRepo: null,
                  supplierPhone: null,
                }
              }
              if (point == null) {
                point = {
                  pointId: null,
                  lon: null,
                  lat: null,
                }
              }
              tableData.push({
                seq: device.deviceId,
                pointId: point.pointId == null ? '': point.pointId,
                supplyId: supply.supplierId == null ? '': supply.supplierId,
                name: device.deviceName,
                deviceType: device.deviceType,
                deviceState: device.state,
                deviceIsValid:device.isValid,
                supplierName: supply.supplierName == null ? '': supply.supplierName,
                supplyRepo: supply.supplierRepo == null ? '': supply.supplierRepo,
                supplyPhone: supply.supplierPhone == null ? '': supply.supplierPhone,
                number: device.number,
                imei: device.imei,
                description: device.description,
                position: point.lon == null ? '': point.lon + "," + point.lat == null ? '': point.lon + "," + point.lat
              });
            }
            self.list = tableData;
            self.loading = false;
          })
          .catch(err => {
            console.log(err);
            self.loading = false;
          });
      },
      typeFormat(row, column) {
        return this.selectDictLabel(this.optionsFrom.typeOptions, row.deviceType);
        // let i = this.$refs.typeSelector.getItem(row.deviceType);
        // return (i && i.label) || "";
      },
      stateFormat(row, column) {
        let i = this.$refs.statusSelector.getItem(row.deviceState);
        return (i && i.label) || "";
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 停用按钮操作 */
      handleDisable(row) {
        var self = this;
        this.$confirm('确认要停用' + row.name + '设备吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          var obj = {
            isValid: "1",
            deviceId: row.seq
          };
          changeIsValid(obj).then(response => {
            if (response.code === 200) {
              self.msgSuccess("停用成功");
              self.getList();
            } else {
              self.msgError(response.msg);
            }
          });
        }).catch((error)=>{
					console.log(error);
				});
      },
      /** 启用按钮操作 */
      handleEnable(row) {
        var self = this;
        this.$confirm('确认要启用' + row.name + '设备吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          var obj = {
            isValid: "0",
            deviceId: row.seq
          };
          changeIsValid(obj).then(response => {
            if (response.code === 200) {
              self.msgSuccess("启用成功");
              self.getList();
            } else {
              self.msgError(response.msg);
            }
          }).catch((error)=>{
            console.log(error);
          });
        }).then(()=>{

        }).catch((error)=>{
          self.loading = false;
					console.log(error);
				});
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "设备导入";
        this.upload.open = true;
      },
      /** 导出按钮操作 */
      handleExport() {
		    let self = this;
        let loading = undefined;
        const queryParams = self.queryParams;
        self.$confirm("是否确认导出所有数据?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(function() {
            loading = self.$loading(self.exportLoading);
            return exportOtherDevice(queryParams);
          })
          .then(response => {
            this.download(response.msg);
			      self.msgSuccess("导出成功");
			      loading.close();
          })
          .catch(function() {
			      if (loading!=undefined) {
              loading.close();
            }
		      });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.$refs.add.handleClick({
          title: "添加设备",
          submit: this.handleSubmit
        });
      },
      /** 编辑按钮操作 */
      handleEdit(row) {
        this.$refs.add.handleClick({
          info: row,
          title: "编辑设备",
          submit: this.handleSubmit
        });
      },
      /** 提交操作 新增 编辑 */
      handleSubmit(info) {
        return Promise.resolve(true); //操作成功 返回
        return Promise.resolve(false); //操作失败 返回
      },
      /** 下载模板操作 */
      importTemplate() {
        let self = this;
        let loading = self.$loading(self.exportLoading);
        importTemplate().then(response => {
          this.download(response.msg);
          loading.close();
        }).catch((error)=>{
          loading.close();
					console.log(error);
				});;
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", {
          dangerouslyUseHTMLString: true
        });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }
    }
  };
</script>
